package org.automated.realestatemanager.db.services;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.log4j.Logger;
import org.automated.realestatemanager.db.entity.Phone;
import org.automated.realestatemanager.db.util.HibernateUtility;

public class PhoneService extends CommonService<Phone> {

	private final Logger log = Logger.getLogger(PhoneService.class);

	public PhoneService() {
		super(Phone.class);
	}

	public Phone getByPhone(final String phone) {
		final List<Phone> result = HibernateUtility.getSession()
				.createQuery("from Phone WHERE phone = :p")
				.setString("p", phone).list();
		if (result == null)
			return null;
		else if (result.size() == 0)
			return null;
		else if (result.size() == 1)
			return result.get(0);
		else
			throw new RuntimeException(
					"More then 1 phone number found in database : " + phone);
	}

	public final Set<Phone> persistPhones(final Set<Phone> phones) {
		final Set<Phone> result = new TreeSet<Phone>();
		log.debug("\n\nPersisting phones: " + phones);
		for (final Phone phone : phones) {
			if (getByPhone(phone.getPhone()) != null) {
				result.add(getByPhone(phone.getPhone()));
			} else {
				result.add(create(phone));
			}
		}
		log.debug("\n\nPersisting phones: " + phones);
		return result;
	}

}
